import axios, { AxiosRequestConfig } from 'axios';
import env from '../env.json'
import { UserContext } from 'modules/User'


const { httpBaseUrl } = env;

let deviceInfo = {
	appId: "1.0.0",
	devType: "14",
};

const httpInit = axios.create({
	timeout: 10000,
});

export async function configHttp() {
	httpInit.interceptors.request.use(async (config) => {
		const { url } = config;
		Object.keys(deviceInfo).forEach((key) => {
			config.headers.common[key] = deviceInfo[key];
		})
		let { user } = UserContext
		if (user.userId) {
			config.headers.common.userId = user.userId;
			config.headers.common.token = user.token;
		}
		if (url && url.indexOf('http') !== 0) {
			config.url = httpBaseUrl + config.url
		}

		return config;
	})
	httpInit.interceptors.response.use((res) => {
		console.log('res', res)
		const body = res.data;
		if (body.code === 401) {
			// store.dispatch({ type: "SIGN_OUT" })
			throw body;
		}
		else if (parseInt(body.code, 10) !== 200) {
			console.error(body)
		}
		return body;

	}, (error) => {
		console.warn('request error', error);
		return Promise.reject(error)
	});
	return httpInit
}


configHttp()

export default httpInit